# coding=utf-8
import time

from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager
from django.core.mail import send_mail
from django.db import models
from django.db.models import signals
from django.utils import timezone
from django.utils.http import urlquote
from django.utils.translation import ugettext_lazy as _
from account.fields import AvatarField
from team.models import TeamMemberShip


class UserManager(BaseUserManager):
    def _create_user(self, nickname, email, password,
                     is_staff, is_superuser, **extra_fields):
        """
        Creates and saves a User with the given username, email and password.
        """
        now = timezone.now()
        if not nickname:
            raise ValueError('The given nickname must be set')
        email = self.normalize_email(email)
        if not email:
            raise ValueError('The given email must be set')
        user = self.model(nickname=nickname, email=email,
                          is_staff=is_staff, is_active=True,
                          is_superuser=is_superuser, last_login=now,
                          date_joined=now, **extra_fields)
        user.set_password(password)
        user.save()
        return user

    def create_user(self, nickname, email=None, password=None, **extra_fields):
        return self._create_user(nickname, email, password, False, False,
                                 **extra_fields)

    def create_superuser(self, nickname, email, password, **extra_fields):
        return self._create_user(nickname, email, password, True, True,
                                 **extra_fields)


class User(AbstractBaseUser, PermissionsMixin):
    """
    An abstract base class implementing a fully featured User model with
    admin-compliant permissions.

    nickname, password and email are required. Other fields are optional.
    """
    nickname = models.CharField(
        '昵称',
        max_length=16,
    )

    email = models.EmailField(_('email address'), unique=True)

    avatar = AvatarField('头像', upload_to='avatar', blank=True)

    is_staff = models.BooleanField(_('staff status'), default=False,
                                   help_text=_('Designates whether the user can log into this admin '
                                               'site.'))
    is_active = models.BooleanField(_('active'), default=True,
                                    help_text=_('Designates whether this user should be treated as '
                                                'active. Unselect this instead of deleting accounts.'))
    activation_token = models.CharField(
        _('activation token'),
        max_length=32,
        blank=True,
    )

    date_joined = models.DateTimeField(_('date joined'), default=timezone.now)

    objects = UserManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['nickname']

    class Meta:
        verbose_name = _('user')
        verbose_name_plural = _('users')
        swappable = 'AUTH_USER_MODEL'

    def __init__(self, *args, **kwargs):
        super(User, self).__init__(*args, **kwargs)

    def get_absolute_url(self):
        return "/users/%s/" % urlquote(self.username)

    def get_full_name(self):
        """
        Returns the first_name plus the last_name, with a space in between.
        """
        return self.nickname.strip()

    def get_short_name(self):
        """
        Returns the short name for the user.
        """
        return self.nickname

    def email_user(self, subject, message, from_email=None):
        """
        Sends an email to this User.
        """
        send_mail(subject, message, from_email, [self.email])

    def has_team(self):
        return self.team_set.exists()

    def delete(self, using=None):
        if not self.has_team():
            super(User, self).delete(using)

    def can_admin_team(self, team):
        try:
            ship = TeamMemberShip.objects.get(member=self, team=team)
        except TeamMemberShip.DoesNotExist:
            return False
        else:
            return ship.can_admin


def post_init(instance, **kwargs):
    instance.old_avatar = instance.avatar


def post_save(instance, **kwargs):
    if hasattr(instance, 'old_avatar'):
        if instance.old_avatar and instance.old_avatar != instance.avatar:
            instance.old_avatar.storage.delete(instance.old_avatar.name)
        del instance.old_avatar


signals.post_init.connect(post_init, sender=User)
signals.post_save.connect(post_save, sender=User)
